package com.bookstore.controller;

import com.bookstore.domain.Book;
import com.bookstore.domain.BookType;
import com.bookstore.domain.Error;
import com.bookstore.domain.User;
import com.bookstore.service.BookService;
import com.bookstore.service.BookTypeService;
import com.bookstore.utils.JsonUtils;
import com.bookstore.utils.UuidUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("book")
public class BookController {
    @Autowired
    private BookTypeService bookTypeService;
    @Autowired
    private BookService bookService;

    /**
     * 获取书籍分类
     * @return
     */
    @RequestMapping(value = "/getType.do")
    @ResponseBody
    public String getType() {
        List<BookType> types = bookTypeService.findAll();
        return JsonUtils.writeValueAsString(types);
    }

    /**
     * 获取所有书籍信息
     * @param start
     * @param pageSize
     * @param req
     * @return
     */
    @RequestMapping(value = "/getBooks.do")
    @ResponseBody
    public String getBooks(Integer start, Integer pageSize, HttpServletRequest req) {
        //处理数据
        if (start == null) {
            start = 1;
        }
        if (pageSize == null) {
            pageSize = 5;
        }
        //获取书籍类型
        String btypestr = req.getParameter("btype");
        Integer btype = 0;
        if (btypestr != null) {
            btype = Integer.parseInt(btypestr);
        }
        String bname = req.getParameter("bname");
        if (bname != null && bname.equals("")) {
            //重置搜索信息
            bname = null;
            btype = 0;
        }
        //设置分页
        PageHelper.startPage(start, pageSize);
        List<Book> books = bookService.findAll(btype, bname);

        //分页处理
        PageInfo<Book> pageInfo = new PageInfo<Book>(books);
        return JsonUtils.writeValueAsString(pageInfo);
    }

    //跳转到添加书籍
    @RequestMapping("addBook.do")
    public String addBook() {
        return "addBook";
    }

    //用于页面图片下载
    @RequestMapping("/download")
    public void download(String img, HttpServletResponse response)  throws Exception{
        String dir = "F:\\book_store\\";
        File file = new File(dir, img);
        FileInputStream fis = new FileInputStream(file);
        ServletOutputStream sos = response.getOutputStream();
        byte[] bytes = new byte[5120];
        int len;
        while ((len = fis.read(bytes)) != -1) {
            sos.write(bytes, 0, len);
        }
        fis.close();
    }

    //添加操作
    @RequestMapping(value = "doAddBook.do")
    @ResponseBody
    public String doAddBook(Book book, @RequestParam("upload") MultipartFile upload, @RequestParam("booktype") String btypestr, HttpServletRequest req) {
        User loginUser = (User) req.getSession().getAttribute("loginUser");
        Error er = new Error();
        if (loginUser != null) {
            if (loginUser.getStatus() == 2 || loginUser.getStatus() == 1) { //商家 和管理员
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String res = sdf.format(new Date());
                //获取登录用户
                System.out.println(book);
                //获取上传的原始文件名
                String filename = upload.getOriginalFilename();
//        System.out.println(filename);
                //获取图片存储路径
                String realPath = "F:\\book_store\\images";/*req.getServletContext().getRealPath("/images");*/
//        System.out.println(realPath);
                String newName = "bk_" + res + UuidUtil.getUuid().substring(0, 5) + filename;
//                System.out.println(newName);
//                修改bean
                //设置封面图路径
                book.setBigImg("/images/" + newName);
                //设置Uid
                book.setUid(loginUser.getUid());
                BookType bkt = new BookType();
                int btype = 0;
                if (btypestr != null) {
                    btype = Integer.parseInt(btypestr);
                }
                bkt.setBtype(btype);
                book.setBtype(bkt);
                //判断文件夹是否存在
                File file = new File(realPath);
                if (!file.exists()) { //判断文件夹是否存在
                    file.mkdirs(); //不存在就创建
                }
                try {
                    //获取文件的字节数组
                    bookService.save(book);
                    upload.transferTo(new File(file, newName));//将文件写入磁盘
//                    System.out.println(book);
                } catch (Exception e) {
                    er.setErrorType(3);
                    er.setErrorInfo("上传书籍失败，请稍后再试。");
                    return "JsonUtils.writeValueAsString(er)";
                }
                er.setErrorType(0);
                er.setErrorInfo("上架成功！");
            } else {
                er.setErrorType(4);
                er.setErrorInfo("抱歉，您的权限不够请先联系管理员注册商家");
            }
        } else {
            er.setErrorType(1);
            er.setErrorInfo("请先登录。。");
        }
        return JsonUtils.writeValueAsString(er);
    }

    /**
     * 根据书的类型获取书籍信息
     * @param start
     * @param pageSize
     * @param req
     * @return
     */
    @RequestMapping(value = "/getBooksByUtype.do")
    @ResponseBody
    public String getBooksByUtype(Integer start, Integer pageSize, HttpServletRequest req) {
        User user = (User) req.getSession().getAttribute("loginUser");
        Integer utype = 0;
        if (user != null) {
            utype = user.getuType();
        }
        //处理数据
        if (start == null) {
            start = 1;
        }
        if (pageSize == null) {
            pageSize = 5;
        }
        String btypestr = req.getParameter("btype");
        Integer btype = 0;
        if (btypestr != null) {
            btype = Integer.parseInt(btypestr);
        }
        String bname = req.getParameter("bname");

        //设置分页规格
        PageHelper.startPage(start, pageSize);
        List<Book> books = null;
        if (utype == 1) { //商家
            books = bookService.findByUtype(utype, btype, bname);
        } else if (utype == 2) { //管理员
            System.err.println("utype==>" + utype + ",btype==>" + btype + ",bname==>" + bname);
            books = bookService.findByUtype(utype, btype, bname);
            System.err.println(books);
        } else {
            return null;
        }
        //分页操作
        PageInfo<Book> pages = new PageInfo<Book>(books);
        return JsonUtils.writeValueAsString(pages);
    }

    /**
     * 根据书的id查单本书籍
     *
     * @param bid
     * @return
     */
    @RequestMapping("/getBookByBid.do")
    @ResponseBody
    public String getBookByBid(Integer bid) {
        Book book = bookService.findByBid(bid);
        return JsonUtils.writeValueAsString(book);
    }
    /**
     * 书籍修改模块
     */
    @RequestMapping("/updateBook.do")
    @ResponseBody
    public String updateBook(Book book) {
//        System.err.println(book);
        int result = bookService.updateBook(book);
        Error error = new Error();
        if(result == 1){
            error.setErrorType(0);
            error.setErrorInfo("修改成功！");
        }else {
            error.setErrorType(5);
            error.setErrorInfo("修改失败！");
        }
        return JsonUtils.writeValueAsString(error);
    }
    /**
     * 删除书籍模块
     */
    @RequestMapping("/delBook")
    @ResponseBody
    public String del(Integer bid){
        Error error = new Error();
        System.err.println(bid);
        int result = bookService.delByBid(bid);
        System.err.println(result);
        if(result == 1){
            error.setErrorType(0);
            error.setErrorInfo("删除成功！");
        }else {
            error.setErrorType(5);
            error.setErrorInfo("删除失败，请稍后再试！");
        }
        return JsonUtils.writeValueAsString(error);
    }
}
